package com.sc.byahi.user.client.components.maps.places;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.shared.HandlerRegistration;
import com.sc.byahi.user.client.components.maps.MVCObject;
import com.sc.byahi.user.client.components.maps.MapImpl;

public class Autocomplete extends MVCObject<Autocomplete> {
	protected Autocomplete() {
	}

	private static final native JavaScriptObject createJso(Element inputField, AutocompleteOptions options) /*-{
		return new $wnd.google.maps.places.Autocomplete(inputField, options);
	}-*/;

	public static final Autocomplete newInstance(Element inputField, AutocompleteOptions options) {
		return createJso(inputField, options).cast();
	}

	public final native PlaceResult getPlace() /*-{
		return this.getPlace();
	}-*/;

	public final native void bindTo(MapImpl map) /*-{
		this.bindTo('bounds', map);
	}-*/;

	public final HandlerRegistration addPlaceCHangeHandler(PlaceChangeMapHandler handler) {

		final JavaScriptObject listener = addPlaceChangeHandlerImpl(this, "place_changed", handler);

		HandlerRegistration registration = new HandlerRegistration() {
			@Override
			public void removeHandler() {
				removeHandlerImpl(listener);
			}
		};
		return registration;
	}

	private static native void removeHandlerImpl(JavaScriptObject listener) /*-{
		$wnd.google.maps.event.removeListener(listener);
	}-*/;

	private static native JavaScriptObject addPlaceChangeHandlerImpl(JavaScriptObject jso, String eventName, PlaceChangeMapHandler handler) /*-{
		var callback = function(event) {
			$entry(@com.sc.byahi.user.client.components.maps.places.PLaceChangeHandlerRegistration::onCallback(Lcom/sc/byahi/user/client/components/maps/places/PlaceChangeMapHandler;Lcom/google/gwt/ajaxloader/client/Properties;)(handler, event));
		};
		return $wnd.google.maps.event.addListener(jso, eventName, callback)
	}-*/;
}
